//
//  InformDetailsController.m
//  Village
//
//  Created by 程虎 on 2017/9/13.
//  Copyright © 2017年 程虎. All rights reserved.
//

#import "InformDetailsController.h"
#import "InformDetailsCell1.h"
#import "InformDetailsCell.h"
#import "TZGGHttpTools.h"
#import "ProgressView.h"
#import "AccessoryTableViewCell.h"
#import "LCDownloadManager.h"
#import "DocumentViewController.h"
@interface InformDetailsController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) AnnounModel *model;
@property (nonatomic, strong) NSMutableArray *mineAry;
@property (nonatomic, strong) NSMutableArray *otherAry;
@property (nonatomic, strong) UITableView *tabView;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic ,strong) NSArray *fijiary;
@property (nonatomic, assign) NSInteger pageCount;//总页数 
@property (nonatomic, strong) UIView *replayViews;
@property (nonatomic, strong) ProgressView *prossView;
@end

@implementation InformDetailsController

- (void)setParams:(id)obj block:(LongriseRouterBlock)block
{
    self.model = (AnnounModel *)obj;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"通知公告";
    _fijiary = [NSArray array];
    _fijiary = [Tools toJSONData:self.model.bulletinfile];
    NSLog(@"--------fijiary：%@",_fijiary);
    [self config_UI];
}

- (void)config_UI
{
    CGFloat height = 44 + kNavHeight;
    self.pageNum = 0;
    self.pageCount = 0;
    [self creatRevertView];
    
    self.tabView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H - height) style:UITableViewStylePlain];
    self.tabView.delegate = self;
    self.tabView.dataSource = self;
    self.tabView.backgroundColor = [Util colorWithHexString:@"#f9f9f9"];
    self.tabView.showsVerticalScrollIndicator = NO;
    self.tabView.showsHorizontalScrollIndicator = NO;
    self.tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tabView];
    
    if (@available(iOS 11.0, *)) {
        self.tabView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [self.tabView registerClass:[AccessoryTableViewCell class] forCellReuseIdentifier:@"AccessoryTableViewCell"];
    [self.tabView registerNib:[UINib nibWithNibName:@"InformDetailsCell1" bundle:nil] forCellReuseIdentifier:@"InformDetailsCell1"];
    [self.tabView registerNib:[UINib nibWithNibName:@"InformDetailsCell" bundle:nil] forCellReuseIdentifier:@"InformDetailsCell"];

    self.tabView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshheader_data)];
    [self.tabView.mj_header beginRefreshing];
    
    self.tabView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshfoot_data)];
}

#pragma mark - 下拉刷新
- (void)refreshheader_data
{
    self.pageNum = 1;
    self.pageCount = 0;
    [self.tabView.mj_footer setState:MJRefreshStateIdle];
    [self getTZGGDetails:self.pageNum];
}
#pragma mark - 上拉刷新
- (void)refreshfoot_data
{
    self.pageNum += 1;
    if (self.pageNum < self.pageCount + 1) {
        [self getTZGGDetails:self.pageNum];
    }
    else {
        [self.tabView.mj_footer endRefreshingWithNoMoreData];
    }
}
#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return (self.fijiary.count > 0 ? 1 : 0)+ (self.mineAry.count > 0 ? 1 : 0) + (self.otherAry.count  > 0 ? 1 : 0) + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1) {
//        return self.mineAry.count > 0 ? self.mineAry.count : (self.otherAry.count > 0 ? self.otherAry.count : 0);
        if (_fijiary.count > 0){
            return _fijiary.count;
        }else if (_mineAry.count > 0){
            return _mineAry.count;
        }else{
            return _otherAry.count;
        }
    }else if (section == 2){
        if (_mineAry.count > 0&&_fijiary.count > 0){
             return _mineAry.count;
        }else{
          return _otherAry.count;
           
        }
    }else{
         return _otherAry.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        InformDetailsCell1 *cell = [InformDetailsCell1 cellWithTableView:tableView];
        cell.model = self.model;
        cell.line.hidden = YES;
//        cell.backgroundColor = [UIColor yellowColor];
        return cell;
    }else if (indexPath.section == 1) {
        if (_fijiary.count > 0){
            UITableViewCell *cell = nil;
            cell = [tableView dequeueReusableCellWithIdentifier:@"AccessoryTableViewCell"];
            AccessoryTableViewCell *newcell = (AccessoryTableViewCell *)cell;
            NSDictionary *dict = self.fijiary[indexPath.row];
            newcell.fjStr = dict[@"httpurl"];
            newcell.Acclable.text = _fijiary[indexPath.row][@"title"];
            [newcell setSelectionStyle:UITableViewCellSelectionStyleNone];//cell点击之后没有视觉效果
            WeakSelf(weakSelf);
            newcell.downBlock = ^(NSInteger index) {
                if ([Globle getInstance].account.userid.length) {
                    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
                    NSString *filePath = [path stringByAppendingPathComponent:@"policy.plist"];
                    // 解档
                    NSMutableArray *usersary = [[NSMutableArray alloc]initWithContentsOfFile:filePath];
                    BOOL isbool = [usersary containsObject: dict[@"httpurl"]];
                    if (isbool == 1){
                        DocumentViewController *document = [[DocumentViewController alloc] init];
                        document.url = dict[@"httpurl"];
                        document.name = dict[@"title"];
                        [self.navigationController pushViewController:document animated:YES];
//                        [MBProgressHUD showError:@"暂不支持阅览" toView:weakSelf.navigationController.view];
                    }else{
                        [weakSelf downloadFjWithIndex:indexPath.row];
                    }
                }
                else {
                    [MBProgressHUD showError:@"下载之前请先登录您的账号！" toView:weakSelf.navigationController.view];
                }
            };
            return cell;
        }else if (_mineAry.count > 0){
            InformDetailsCell *cell = [InformDetailsCell cellWithTableView:tableView];
            cell.model = self.mineAry.count > 0 ? self.mineAry[indexPath.row] : self.otherAry[indexPath.row];
            cell.line.hidden = self.mineAry.count > 0 ? NO : YES;
            return cell;
        }else{
            InformDetailsCell *cell = [InformDetailsCell cellWithTableView:tableView];
            cell.model = self.otherAry[indexPath.row];
            cell.line.hidden = self.otherAry.count > 0 ? NO : YES;
            return cell;
        }
        
    }else if(indexPath.section == 2) {
        if (_mineAry.count > 0&&_fijiary.count>0){
            InformDetailsCell *cell = [InformDetailsCell cellWithTableView:tableView];
            cell.model = self.mineAry.count > 0 ? self.mineAry[indexPath.row] : self.otherAry[indexPath.row];
            cell.line.hidden = self.mineAry.count > 0 ? NO : YES;
            return cell;
        }else{
            InformDetailsCell *cell = [InformDetailsCell cellWithTableView:tableView];
            cell.model = self.otherAry[indexPath.row];
            cell.line.hidden = self.otherAry.count > 0 ? NO : YES;
            return cell;
        }
    }else{
        InformDetailsCell *cell = [InformDetailsCell cellWithTableView:tableView];
        cell.model = self.otherAry[indexPath.row];
        cell.line.hidden = self.otherAry.count > 0 ? NO : YES;
        return cell;
    }
        

}


- (void)downloadFjWithIndex:(NSInteger )index
{
    self.prossView = [[ProgressView alloc] init];
    [self.prossView show];
    
    NSDictionary *dict = self.fijiary[index];
    
    NSMutableArray *fileAry = [NSMutableArray array];
    NSMutableArray *nameAry = [NSMutableArray array];
    [fileAry addObject:dict[@"httpurl"]];
    [nameAry addObject:[NSString stringWithFormat:@"%@",dict[@"httpurl"]]];
    [[LCDownloadManager getInstanceWithuserflag:[Globle getInstance].account.userid withStoragePath:@"down_fj"] downloadFileWith:fileAry withNameArr:nameAry progressbloack:^(CGFloat progress, long long totalMBRead, long long totalMBExpectedToRead) {
        self.prossView.prossCount = progress;
    } successBlock:^(NSString *sucDownPath, NSString *SucDownName) {
        [self.prossView hide];
        NSDictionary *FJDict = [NSMutableDictionary dictionary];
        FJDict = [Util getDataForKey:[Globle getInstance].account.userid.length > 0 ? [Globle getInstance].account.userid : @""];
        NSArray *arys = FJDict[@"id"];
        NSMutableArray *arrays = [NSMutableArray arrayWithArray:arys];
        NSMutableDictionary *dataDict = [NSMutableDictionary dictionary];
        if ([[FJDict allKeys] count]) {
            for (int i = 0; i < arys.count; i++) {
                if (![arys[i] isEqualToString:dict[@"httpurl"]]) {
                    [arrays addObject:dict[@"httpurl"]];
                    [dataDict setObject:arrays forKey:@"id"];
                    [self addary:dict[@"httpurl"]];
                }
            }
        }
        else {
            [arrays addObject:dict[@"httpurl"]];
            [dataDict setObject:arrays forKey:@"id"];
            [self addary:dict[@"httpurl"]];
        }
        [[Globle getInstance] saveAttachment:dataDict];
        [_tabView reloadData];
    } failureBlock:^(NSError *error, NSString *errorDownPath, NSString *errorDowName) {
        [MBProgressHUD showError:@"下载失败，请检查您的网络重新下载！" toView:self.navigationController.view];
    }];
}
#pragma mark - 储存本地
- (void)addary:(NSString *)idd{
    //                    ----------
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [path stringByAppendingPathComponent:@"policy.plist"];
    // 解档
    NSMutableArray *usersary = [[NSMutableArray alloc]initWithContentsOfFile:filePath];
    if (usersary.count == 0){
        usersary = [NSMutableArray array];
    }
    [usersary addObject:idd];
    [Tools Dictionariesplistname:usersary];
    //                    ----------
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_fijiary.count > 0 && indexPath.section == 1){
        return 50;
    }else{
        Class currentClass = [InformDetailsCell1 class];
        id model = nil;
        if (indexPath.section == 0) {
            model = self.model;
        }else {
            if (indexPath.section == 1) {
                model = self.mineAry.count > 0 ? self.mineAry[indexPath.row] : self.otherAry[indexPath.row];
            }else {
                model = self.otherAry.count > 0 ? self.otherAry[indexPath.row] : nil;
            }
            currentClass = [InformDetailsCell class];
        }
        return [self.tabView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:currentClass contentViewWidth:[self cellContentViewWith]] ;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section != 0) {
        if (section == 1 &&_fijiary.count > 0){
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, 40)];
            view.backgroundColor = [UIColor whiteColor];
            UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 50, 30)];
            lab.text = @"附件";
            lab.font = [UIFont systemFontOfSize:15];
            [view addSubview:lab];
            return view;
        }else{
             return [self creatHeaderViewWithSection:section];
        }
    }
    else {
        return nil;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *views = [UIView new];
    views.backgroundColor = [Util colorWithHexString:@"#f9f9f9"];
    return views;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return tableView.numberOfSections > 1 ? 10 : 0.001;
    }
    else {
        return 0.001;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section != 0) {
        return 43.5;
    }
    else {
        return 0.001;
    }
}
- (CGFloat)cellContentViewWith
{
    //contentViewWidth  一定要计算cell的宽度  计算出来的高度 才是准确的
    CGFloat width = SCREEN_W ;
    // 适配ios7横屏
    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait && [[UIDevice currentDevice].systemVersion floatValue] < 8) {
        width = [UIScreen mainScreen].bounds.size.height;
    }
    return width;
}
#pragma mark - headerView
- (UIView *)creatHeaderViewWithSection:(NSInteger )index
{
    UIView *views = [[UIView alloc] initWithFrame:CGRectMake(0, 13.5, SCREEN_W, 30)];
    views.backgroundColor = [UIColor whiteColor];
    UIImageView *img = [UIImageView new];
    [views addSubview:img];
    if(((_fijiary.count > 0 && index == 2)||(_fijiary.count == 0&&index == 1)) && (_mineAry.count > 0)){
        img.sd_layout
        .leftSpaceToView(views, 0)
        .centerYEqualToView(views)
        .widthIs(120)
        .heightIs(30);
    }else{
        img.sd_layout
        .leftSpaceToView(views, 0)
        .centerYEqualToView(views)
        .widthIs(84.5)
        .heightIs(30);
    }
   
    
    UILabel *lab = [[Tools shareInstance] creat_Label:@"" Color:[UIColor whiteColor] Font:14 tag:-1 Alignment:0 Lines:1];
    [img addSubview:lab];
    
    if (((_fijiary.count > 0 && index == 2)||(_fijiary.count == 0&&index == 1)) && (_mineAry.count > 0)){
        lab.sd_layout
        .leftSpaceToView(img, 10)
        .centerYEqualToView(img)
        .widthRatioToView(img, 1)
        .heightRatioToView(img, 1);
    }else{
        lab.sd_layout
        .leftSpaceToView(img, 10)
        .centerYEqualToView(img)
        .widthRatioToView(img, 1)
        .heightRatioToView(img, 1);
    }
    
   
    

    if (_fijiary.count > 0){
        if (self.mineAry.count) {
            img.image = [UIImage imageNamed:index == 2 ? @"myback" : @"other_inform"];
            lab.text = index == 2 ? @"我的最新回复" : @"精彩回复";
        }
        else {
            img.image = [UIImage imageNamed:@"other_inform"];
            lab.text = @"精彩回复";
        }
    }else{
        if (self.mineAry.count) {
            img.image = [UIImage imageNamed:index == 1 ? @"myback" : @"other_inform"];
            lab.text = index == 1 ? @"我的最新回复" : @"精彩回复";
        }
        else {
            img.image = [UIImage imageNamed:@"other_inform"];
            lab.text = @"精彩回复";
        }
    }
   
    
    return views;
}

#pragma mark - 回复按钮
#pragma mark - headerView
- (void)creatRevertView
{
    self.replayViews = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_H - kNavHeight - 44, SCREEN_W, 44)];
    self.replayViews.backgroundColor = [Util colorWithHexString:@"#f9f9f9"];
    [self.view addSubview:self.replayViews];
    
    UIImageView *line = [UIImageView new];
    line.backgroundColor = [Util colorWithHexString:@"#cccccc"];
    
    UIView *views = [UIView new];
    views.backgroundColor = [UIColor whiteColor];
    LRViewRadius(views, 5, 0.5, [Util colorWithHexString:@"#e5e5e5"]);
    
    UILabel *lab = [[Tools shareInstance] creat_Label:@"回复" Color:[Util colorWithHexString:@"#9fa5af"] Font:15 tag:-1 Alignment:0 Lines:1];
    [views addSubview:lab];
    
    UIImageView *img = [UIImageView new];
    img.image = [UIImage imageNamed:@"sendout_annucement"];
    
    UIButton *btn = [[Tools shareInstance] creat_Button:@"" Color:[UIColor clearColor] BackColors:[UIColor clearColor] Font:16 tag:0];
    [btn addTarget:self action:@selector(btnClickBlock) forControlEvents:UIControlEventTouchUpInside];
    [self.replayViews sd_addSubviews:@[line,views,img,btn]];
    
    line.sd_layout
    .leftSpaceToView(self.replayViews, 0)
    .topSpaceToView(self.replayViews, 0)
    .rightSpaceToView(self.replayViews, 0)
    .heightIs(1);
    
    img.sd_layout
    .rightSpaceToView(self.replayViews, 10)
    .centerYEqualToView(self.replayViews)
    .widthIs(30)
    .heightEqualToWidth();
    
    views.sd_layout
    .leftSpaceToView(views, 10)
    .centerYEqualToView(img)
    .rightSpaceToView(img, 10)
    .heightIs(34);
    
    lab.sd_layout
    .leftSpaceToView(views, 13)
    .centerYEqualToView(views)
    .widthIs(50)
    .heightIs(14);
    
    btn.sd_layout
    .spaceToSuperView(UIEdgeInsetsZero);
}

- (void)btnClickBlock
{
    id obj = [LongriseRouter openURL:@"RevertAnnucetementController"];
    if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
    {
        id<LongriseRouterDelegater> delegater = obj;
        if(delegater)
        {
            //进行传值，传入统一的block以供B进行回调
            [delegater setParams:self.model block:^(id obj) {
            
                //回复之后刷新数据 隐藏回复按钮
//                self.replayViews.frame = CGRectMake(0, SCREEN_H - kNavHeight, SCREEN_W, 44);
//                self.tabView.frame = CGRectMake(0, 0, SCREEN_W, SCREEN_H - kNavHeight);
                [self getTZGGDetails:1];
                NSLog(@"回调数据：%@",obj);
            }];
        }
    }
    if (obj && [obj isKindOfClass:[UIViewController class]]) {
        UIViewController *VC = obj;
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:VC];
        [self presentViewController:nav animated:YES completion:nil];
    }
}
#pragma mark - 通知公告详情
- (void)getTZGGDetails:(NSInteger )index
{
    [MBProgressHUD showMessage:@"正在查询..." toView:self.navigationController.view];
    WeakSelf(weakSelf);
    [TZGGHttpTools GetTZGGDetailsPageNum:index WithArticlesID:self.model.bulletinid Success:^(NSDictionary *valueDict) {
        [MBProgressHUD hideHUDForView:weakSelf.navigationController.view];
        if (index == 1) {
            [weakSelf.tabView.mj_header endRefreshing];
            self.pageCount = [valueDict[@"pagecount"] integerValue];
            [self identifyData:[InformModel mj_objectArrayWithKeyValuesArray:valueDict[@"list"]]];
        }
        else {
            [weakSelf.tabView.mj_footer endRefreshing];
            NSMutableArray *arrays = [NSMutableArray arrayWithArray:self.mineAry];
            [arrays addObjectsFromArray:self.otherAry];
            [arrays addObjectsFromArray:[InformModel mj_objectArrayWithKeyValuesArray:valueDict[@"list"]]];
            [self identifyData:arrays];
        }
    } failure:^(NSString *error) {
        [MBProgressHUD hideHUDForView:weakSelf.navigationController.view];
        if (index == 1) {
            [weakSelf.tabView.mj_header endRefreshing];
        }
        else {
            [weakSelf.tabView.mj_footer endRefreshing];
        }
    }];
}

- (void)identifyData:(NSArray *)arrays
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableArray *mineAry = [NSMutableArray array];
        NSMutableArray *otherAry = [NSMutableArray array];
        BOOL ar = YES;
        for (InformModel *model in arrays) {
            BOOL Result = [model.userid compare:[Globle getInstance].account.leapuserid];
            if (Result == 0 && ar == YES) {
                [mineAry addObject:model];
                ar = NO;
              
            }else {
                [otherAry addObject:model];
              
            }
        }
       
        self.mineAry = [NSMutableArray arrayWithArray:mineAry];
        self.otherAry = [NSMutableArray arrayWithArray:otherAry];
          NSLog(@"其他%@----------------",self.otherAry);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tabView reloadData];
        });
    });
}
@end
